package com.gitee.wsl.concurrent

import com.gitee.wsl.logger.Logger
import kotlinx.atomicfu.atomic
import java.util.concurrent.ThreadFactory


/**
 * Common Thread Factory.
 *
 * @author yuanyuan.liu
 */
class KleinThreadFactory private constructor(
    private val namePrefix: String,
    private val daemon: Boolean
) : ThreadFactory {
    override fun newThread(runnable: Runnable): Thread {
        val thread = Thread(
            THREAD_GROUP, runnable,
            THREAD_GROUP.name + "-" + namePrefix + "-" + THREAD_NUMBER.getAndIncrement()
        )
        thread.setDaemon(daemon)
        thread.setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler { t: Thread?, e: Throwable? ->
            Logger.e(
                e!!.message,
                e
            )
        })
        if (thread.priority != Thread.NORM_PRIORITY) {
            thread.setPriority(Thread.NORM_PRIORITY)
        }
        return thread
    }

    companion object {


        private val THREAD_NUMBER = atomic(1L)

        private val THREAD_GROUP = ThreadGroup("klein")

        /**
         * create custom thread factory.
         *
         * @param namePrefix prefix
         * @param daemon     daemon
         * @return [ThreadFactory]
         */
        fun create(namePrefix: String, daemon: Boolean): ThreadFactory {
            return KleinThreadFactory(namePrefix, daemon)
        }
    }
}
